<template>
  <div>
    <div><h1>交易市场</h1></div>
    <div>
      <!-- 查询搜索 -->
      <div class="search_panel">
        <el-form :inline="true">
          <el-form-item label="按项目搜索">
            <el-input
              class="input_class"
              v-model="query.trade_name"
              placeholder="请输入项目名称"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="searchTradeByName"
              >查询</el-button
            >
          </el-form-item>
        </el-form>
      </div>
    </div>
    <div>
      <!-- 显示交易表格 -->
      <div>
        <el-table
          :data="tableData"
          border
          style="width: 100%"
          :row-class-name="tableRowClassName"
        >
          <el-table-column prop="trade_id" label="序号" width="80">
          </el-table-column>
          <el-table-column prop="trade_name" label="对话方" width="240">
            <template slot-scope="scope">
              {{ scope.row.username + "_" + scope.row.enter_name }}
            </template>
          </el-table-column>
          <el-table-column prop="trade_name" label="交易项目名称">
            <template slot-scope="scope">
              {{ scope.row.trade_name }}
            </template>
          </el-table-column>
          <el-table-column prop="industry_name" label="所属行业" width="120">
            <template slot-scope="scope">
              {{ scope.row.industry_name }}
            </template>
          </el-table-column>
          <el-table-column prop="trade_state" label="交易角色" width="80">
            <template slot-scope="scope">
              <el-tag type="success" v-if="scope.row.trade_type == 0">
                {{ setTradeType(scope.row.trade_type) }}</el-tag
              >
              <el-tag type="danger" v-else>
                {{ setTradeType(scope.row.trade_type) }}</el-tag
              >
            </template>
          </el-table-column>
          <el-table-column
            prop="trade_quantity"
            label="报价量(tCO2e)"
            width="140"
          >
          </el-table-column>
          <el-table-column
            prop="trade_offer"
            label="报价(元/tCO2e)"
            width="140"
          >
          </el-table-column>
          <el-table-column prop="publish_time" label="发布时间" width="250">
          </el-table-column>
          <el-table-column prop="trade_state" label="交易状态" width="100">
            <template slot-scope="scope">
              <el-tag type="danger" v-if="scope.row.trade_state == 2">
                {{ setOrderState(scope.row.trade_state) }}</el-tag
              >
              <el-tag type="success" v-else-if="scope.row.trade_state == 1">
                {{ setOrderState(scope.row.trade_state) }}</el-tag
              >
              <el-tag v-else>
                {{ setOrderState(scope.row.trade_state) }}</el-tag
              >
            </template>
          </el-table-column>

          <el-table-column prop="buyer_id" label="交易方式" width="120">
            <template slot-scope="scope">
              <span v-if="scope.row.buyer_id == 0">
                <el-link :underline="false" type="success">场内交易</el-link>
              </span>
              <span v-else>
                <el-link :underline="false" type="primary">场外交易</el-link>
              </span>
            </template>
          </el-table-column>
          <el-table-column class-name="opr" label="操作">
            <template slot-scope="scope">
              <el-link
                :underline="false"
                type="primary"
                @click="handleShow(scope.$index, scope.row)"
                >查看</el-link
              >
              <el-link
                v-if="scope.row.trade_state != 2 && scope.row.trade_type == 1"
                :underline="false"
                type="primary"
                @click="handleBuy(scope.$index, scope.row)"
                >买入</el-link
              >
              <el-link
                v-if="scope.row.trade_state != 2 && scope.row.trade_type == 0"
                :underline="false"
                type="danger"
                @click="handleSell(scope.$index, scope.row)"
                >卖出</el-link
              >
            </template>
          </el-table-column>
        </el-table>
        <div class="pagination">
          <el-pagination
            background
            layout="total, prev, pager, next"
            :current-page="query.currentPage"
            :page-size="query.pageSize"
            :page-count="pageTotal"
            @current-change="handlePageChange"
          ></el-pagination>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { getTradeMarketPagerData,tradeBuyOrder,tradeSellOrder } from "@/api";

export default {
  name: "TradeMarketView",
  data() {
    return {
      user_id: JSON.parse(localStorage.getItem("User")).user_id,
      query: {        
        trade_name: "",
        currentPage: 1,
        pageSize: 10,
      },
      user_state: 0,
      enterpriseData: {},
      tableData: [],
      pageTotal: 0,
      dialogFormVisible: false,
      formData: {
        trade_type: 0,
      },
      form_rules: {
        trade_name: [
          { required: true, message: "请输入项目名称", trigger: "blur" },
        ],
        trade_quantity: [
          { required: true, message: "请输入交易数量", trigger: "blur" },
        ],
        trade_offer: [
          { required: true, message: "请输入单价", trigger: "blur" },
        ],
      },
      //用于交易的表单数据
      tradeFormData: {
        tradeuser_id: JSON.parse(localStorage.getItem("User")).user_id, //为了安全，前后端都验证
      },
    };
  },
  mounted() {
    this.initData();
  },
  methods: {
    //初始化方法
    initData() {
      this.getTradeMarketPagerData();
    },
    //加载交易市场分页数据
    async getTradeMarketPagerData() {
      let res = await getTradeMarketPagerData(this.query);
      // console.log(res);
      if (res.code == 200) {
        this.tableData = res.data.data;
        this.pageTotal = res.data.pageTotal;
      } else {
        //
      }
    },
    //搜索查询按钮
    searchTradeByName() {
      this.getTradeMarketPagerData();
      this.query.trade_name = "";
    },
    //设置订单状态
    setOrderState(num) {
      switch (num) {
        case 0:
          return "未发布";
        case 1:
          return "发布中";
        case 2:
          return "交易完成";
      }
    },
    //设置交易类型
    setTradeType(num) {
      switch (num) {
        case 0:
          return "买方";
        case 1:
          return "卖方";
      }
    },
    tableRowClassName({ row, rowIndex }) {
      if (rowIndex === 1) {
        return "warning-row";
      } else if (rowIndex === 3) {
        return "success-row";
      }
      return "";
    },
    handleShow(index, row) {
      console.log(index, row);
    },
    handleBuy(index, row) {
      if (this.user_id == row.publish_id) {
        //自己不能交易自己
        this.$message.error("不能与自己交易");
      } else {
        this.$confirm("确定要买入吗？", "提示", {
          type: "warning",
        })
          .then(() => {
            this.tradeBuyOrder(row);
          })
          .catch(() => {});
      }
    },
    handleSell(index, row) {
      if (this.user_id == row.publish_id) {
        //自己不能交易自己
        this.$message.error("不能与自己交易");
      } else {
        this.$confirm("确定要卖出吗？", "提示", {
          type: "warning",
        })
          .then(() => {
            this.tradeSellOrder(row);
          })
          .catch(() => {});
      }
    },
    // 分页导航
    handlePageChange(val) {
      // console.log(val);
      // this.$set(this.query, 'currentPage', val);
      this.query.currentPage = val;
      this.initData();
    },
    //交易功能买入
    async tradeBuyOrder(row) {
      //交易用户id
      this.tradeFormData = row;
      this.tradeFormData.tradeuser_id = this.user_id;
      let res = await tradeBuyOrder(this.tradeFormData);
      if(res.code == 200){
        this.$message({
          message: res.msg,
          type: "success",
        });
        //交易成功刷新数据
        this.initData();
      }else{
        this.$message.error(res.msg);
      }
    },
    //交易功能卖出
    async tradeSellOrder(row){
      //交易用户id
      this.tradeFormData = row;
      this.tradeFormData.tradeuser_id = this.user_id;
      let res = await tradeSellOrder(this.tradeFormData);
      if(res.code == 200){
        this.$message({
          message: res.msg,
          type: "success",
        });
        //交易成功刷新数据
        this.initData();
      }else{
        this.$message.error(res.msg);
      }
    },
  },
};
</script>

<style scoped>
.opr .el-link {
  margin-right: 10px;
}
</style>